package com.liuceng.zen.web.tag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.HtmlUtils;

/**
 * CutStringTag.java
 * 
 */
public class CutStringTag extends TagSupport {
  private static final long serialVersionUID = 1638984530467586859L;

  private static Logger logger = LoggerFactory.getLogger(CutStringTag.class);
  /**
   * Logger for this class
   */
  private String value;
  private String escape = "false";

  private String mark = "";
  private Integer size;

  @Override
  public int doStartTag() throws JspException {
    return SKIP_BODY;
  }

  @Override
  public int doEndTag() throws JspException {
    String html = cutString(value, size, mark);
    try {
      pageContext.getOut().write(html.toString());
    } catch (IOException e) {
      logger.error("tag CutStringTag error", e);
    }
    return EVAL_PAGE;
  }

  /**
   * <lotres:cutString size="4" value="我早3333"/>
   * 
   * @param str
   * @param len
   * @param mark
   * @return
   */
  public String cutString(String str, int len, String addationMark) {
    len = len * 2;
    StringBuffer sb = new StringBuffer();
    int counter = 0;
    for (int i = 0; i < str.length(); i++) {
      char curChar = str.charAt(i);
      // 中文两位英文一位
      if (curChar < 255) {
        counter = counter + 1;
      } else {
        counter = counter + 2;
      }
      if (counter > len) {
        String result = sb.toString().trim();
        sb = new StringBuffer(result + addationMark);
        break;
      }
      sb.append(curChar);
    }
    return (getEscape() != null && getEscape().equals("false"))
        ? HtmlUtils.htmlEscape(sb.toString()) : sb.toString();
  }

  public String getValue() {
    return value;
  }

  public void setValue(String value) {
    this.value = value;
  }

  public String getMark() {
    return mark;
  }

  public void setMark(String mark) {
    this.mark = mark;
  }

  public Integer getSize() {
    return size;
  }

  public void setSize(Integer size) {
    this.size = size;
  }

  /**
   * @return the escape
   */
  public String getEscape() {
    return escape;
  }

  /**
   * @param escape the escape to set
   */
  public void setEscape(String escape) {
    this.escape = escape;
  }

}
